#!/bin/bash

# YouTube高效下载脚本
# 使用yt-dlp工具下载YouTube视频

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 默认下载目录
DOWNLOAD_DIR="$HOME/Downloads/YouTube"
# 单个视频下载目录
SINGLE_VIDEO_DIR="$DOWNLOAD_DIR/单个视频"
# 批量下载目录
BATCH_VIDEO_DIR="$DOWNLOAD_DIR/批量下载"
# 默认格式（安全且有音轨优先）：
# 1) 分离流：任意最佳视频 + 任意最佳音频
# 2) 退化到带音轨的单文件（优先 mp4），确保不会无声
# 3) 再退到 18（常见带音轨的 progressive）
DEFAULT_FORMAT="bv*+ba/b[acodec!=none][vcodec!=none][ext=mp4]/b[acodec!=none][vcodec!=none]/18"

# 下载记录文件
DOWNLOAD_LOG="$DOWNLOAD_DIR/download_history.log"
# 同步状态文件
SYNC_STATUS="$DOWNLOAD_DIR/sync_status.json"

# 创建下载目录结构
mkdir -p "$DOWNLOAD_DIR"
mkdir -p "$SINGLE_VIDEO_DIR"
mkdir -p "$BATCH_VIDEO_DIR"

# 当前脚本所在目录（用于定位后处理脚本）
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# 智能同步下载功能（支持增删改）
sync_download() {
    local file="$1"
    local format="$2"
    local output_dir="$3"
    local audio_only="$4"
    local subtitles="$5"
    local verbose="$6"
    local is_playlist="$7"
    
    if [ ! -f "$file" ]; then
        echo -e "${RED}错误: 文件不存在: $file${NC}"
        exit 1
    fi
    
    echo -e "${BLUE}开始智能同步下载，从文件: $file${NC}"
    echo -e "${YELLOW}支持增删改操作，智能同步所有变化${NC}"
    echo ""
    
    # 创建或加载同步状态
    if [ ! -f "$SYNC_STATUS" ]; then
        echo "{}" > "$SYNC_STATUS"
    fi
    
    # 获取当前链接列表的哈希值
    local current_hash=$(get_file_hash "$file")
    local last_hash=$(get_last_hash "$file")
    
    # 分析链接变化
    local changes=$(analyze_changes "$file" "$output_dir" "$is_playlist")
    local added_links=$(echo "$changes" | grep "ADDED:" | wc -l)
    local removed_links=$(echo "$changes" | grep "REMOVED:" | wc -l)
    local modified_links=$(echo "$changes" | grep "MODIFIED:" | wc -l)
    
    echo -e "${BLUE}检测到变化:${NC}"
    echo -e "  新增链接: $added_links"
    echo -e "  删除链接: $removed_links"
    echo -e "  修改链接: $modified_links"
    echo ""
    
    # 处理删除的链接
    if [ $removed_links -gt 0 ]; then
        echo -e "${YELLOW}处理删除的链接...${NC}"
        handle_removed_links "$file" "$output_dir" "$is_playlist"
    fi
    
    # 处理新增和修改的链接
    local count=0
    local new_count=0
    local skip_count=0
    local success=0
    
    while IFS= read -r line || [ -n "$line" ]; do
        # 跳过空行和注释行
        if [[ -z "$line" || "$line" =~ ^[[:space:]]*# ]]; then
            continue
        fi
        
        count=$((count + 1))
        echo -e "${BLUE}[$count]${NC} 检查链接: $line"
        
        # 检查链接状态
        local link_status=$(get_link_status "$line" "$output_dir" "$is_playlist")
        
        case "$link_status" in
            "NEW")
                echo -e "${GREEN}🆕 新链接，开始下载: $line${NC}"
                new_count=$((new_count + 1))
                ;;
            "MODIFIED")
                echo -e "${YELLOW}🔄 链接已修改，重新下载: $line${NC}"
                new_count=$((new_count + 1))
                # 删除旧文件
                remove_old_files "$line" "$output_dir" "$is_playlist"
                ;;
            "EXISTS")
                echo -e "${BLUE}✓ 已存在且未变化，跳过: $line${NC}"
                skip_count=$((skip_count + 1))
                continue
                ;;
        esac
        
        # 如果是播放列表，为每个播放列表创建独立子文件夹
        local current_output_dir="$output_dir"
        if [ "$is_playlist" = "true" ]; then
            # 从URL中提取播放列表名称或ID
            local playlist_name=""
            if [[ "$line" =~ playlist\?list=([^&]+) ]]; then
                playlist_name="${BASH_REMATCH[1]}"
            elif [[ "$line" =~ @([^/]+) ]]; then
                playlist_name="${BASH_REMATCH[1]}"
            else
                playlist_name="playlist_$count"
            fi
            
            # 创建播放列表专用目录
            current_output_dir="$BATCH_VIDEO_DIR/$playlist_name"
            mkdir -p "$current_output_dir"
            echo -e "${YELLOW}创建播放列表目录:${NC} $current_output_dir"
        fi
        
        download_video "$line" "$format" "$current_output_dir" "$audio_only" "$subtitles" "$verbose"
        
        if [ $? -eq 0 ]; then
            success=$((success + 1))
            # 记录下载成功
            record_download "$line" "$current_output_dir" "$is_playlist"
        fi
        
        echo "----------------------------------------"
    done < "$file"
    
    # 更新文件哈希值
    update_file_hash "$file" "$current_hash"
    
    # 保存当前状态
    save_current_links "$file"
    save_content_hash "$file"
    save_link_status "$file" "$output_dir" "$is_playlist"
    
    echo -e "${GREEN}智能同步完成!${NC}"
    echo -e "总计链接: $count"
    echo -e "新增/修改: $new_count"
    echo -e "跳过未变化: $skip_count"
    echo -e "下载成功: $success"
    echo -e "下载失败: $((new_count - success))"
    echo ""
    echo -e "变化统计:"
    echo -e "  新增: $added_links, 删除: $removed_links, 修改: $modified_links"
}

# 检查是否已下载
is_already_downloaded() {
    local url="$1"
    local output_dir="$2"
    local is_playlist="$3"
    
    # 从URL中提取视频ID或播放列表ID
    local video_id=""
    local playlist_id=""
    
    if [[ "$url" =~ watch\?v=([^&]+) ]]; then
        video_id="${BASH_REMATCH[1]}"
    elif [[ "$url" =~ playlist\?list=([^&]+) ]]; then
        playlist_id="${BASH_REMATCH[1]}"
    elif [[ "$url" =~ @([^/]+) ]]; then
        playlist_id="${BASH_REMATCH[1]}"
    fi
    
    if [ -n "$video_id" ]; then
        # 检查单个视频是否已存在
        local video_files=$(find "$output_dir" -name "*$video_id*" -o -name "*$video_id*" 2>/dev/null)
        if [ -n "$video_files" ]; then
            return 0  # 已存在
        fi
    fi
    
    if [ -n "$playlist_id" ]; then
        # 检查播放列表目录是否存在且非空
        local playlist_dir="$BATCH_VIDEO_DIR/$playlist_id"
        if [ -d "$playlist_dir" ] && [ "$(ls -A "$playlist_dir" 2>/dev/null)" ]; then
            return 0  # 已存在
        fi
    fi
    
    return 1  # 不存在
}

# 记录下载信息
record_download() {
    local url="$1"
    local output_dir="$2"
    local is_playlist="$3"
    
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    local record="$timestamp|$url|$output_dir|$is_playlist"
    
    echo "$record" >> "$DOWNLOAD_LOG"
}

# 获取文件哈希值
get_file_hash() {
    local file="$1"
    if [ -f "$file" ]; then
        md5sum "$file" 2>/dev/null | cut -d' ' -f1 || echo "no_hash"
    else
        echo "no_file"
    fi
}

# 获取上次文件哈希值
get_last_hash() {
    local file="$1"
    local file_name=$(basename "$file")
    local hash_file="$DOWNLOAD_DIR/.${file_name}.hash"
    
    if [ -f "$hash_file" ]; then
        cat "$hash_file"
    else
        echo "no_hash"
    fi
}

# 更新文件哈希值
update_file_hash() {
    local file="$1"
    local hash="$2"
    local file_name=$(basename "$file")
    local hash_file="$DOWNLOAD_DIR/.${file_name}.hash"
    
    echo "$hash" > "$hash_file"
}

# 分析链接变化
analyze_changes() {
    local file="$1"
    local output_dir="$2"
    local is_playlist="$3"
    
    local changes=""
    local current_links=$(get_current_links "$file")
    local previous_links=$(get_previous_links "$file")
    
    # 检测新增链接
    while IFS= read -r link; do
        if [ -n "$link" ] && ! echo "$previous_links" | grep -q "$link"; then
            changes="${changes}ADDED:$link"$'\n'
        fi
    done <<< "$current_links"
    
    # 检测删除的链接
    while IFS= read -r link; do
        if [ -n "$link" ] && ! echo "$current_links" | grep -q "$link"; then
            changes="${changes}REMOVED:$link"$'\n'
        fi
    done <<< "$previous_links"
    
    # 检测修改的链接（通过比较文件内容）
    local current_content=$(get_file_content_hash "$file")
    local previous_content=$(get_previous_content_hash "$file")
    
    if [ "$current_content" != "$previous_content" ] && [ "$previous_content" != "no_hash" ]; then
        # 检测哪些链接发生了变化
        while IFS= read -r link; do
            if [ -n "$link" ]; then
                local old_status=$(get_previous_link_status "$link" "$file")
                local new_status=$(get_link_status "$link" "$output_dir" "$is_playlist")
                if [ "$old_status" != "$new_status" ]; then
                    changes="${changes}MODIFIED:$link"$'\n'
                fi
            fi
        done <<< "$current_links"
    fi
    
    echo "$changes"
}

# 获取当前链接列表
get_current_links() {
    local file="$1"
    grep -v '^[[:space:]]*#' "$file" | grep -v '^[[:space:]]*$' | sort
}

# 获取之前的链接列表
get_previous_links() {
    local file="$1"
    local file_name=$(basename "$file")
    local links_file="$DOWNLOAD_DIR/.${file_name}.links"
    
    if [ -f "$links_file" ]; then
        cat "$links_file"
    else
        echo ""
    fi
}

# 保存当前链接列表
save_current_links() {
    local file="$1"
    local file_name=$(basename "$file")
    local links_file="$DOWNLOAD_DIR/.${file_name}.links"
    
    get_current_links "$file" > "$links_file"
}

# 获取文件内容哈希
get_file_content_hash() {
    local file="$1"
    if [ -f "$file" ]; then
        grep -v '^[[:space:]]*#' "$file" | grep -v '^[[:space:]]*$' | sort | md5sum 2>/dev/null | cut -d' ' -f1 || echo "no_hash"
    else
        echo "no_file"
    fi
}

# 获取之前的内容哈希
get_previous_content_hash() {
    local file="$1"
    local file_name=$(basename "$file")
    local content_hash_file="$DOWNLOAD_DIR/.${file_name}.content_hash"
    
    if [ -f "$content_hash_file" ]; then
        cat "$content_hash_file"
    else
        echo "no_hash"
    fi
}

# 保存内容哈希
save_content_hash() {
    local file="$1"
    local file_name=$(basename "$file")
    local content_hash_file="$DOWNLOAD_DIR/.${file_name}.content_hash"
    
    get_file_content_hash "$file" > "$content_hash_file"
}

# 获取链接状态
get_link_status() {
    local url="$1"
    local output_dir="$2"
    local is_playlist="$3"
    
    # 检查是否已下载
    if is_already_downloaded "$url" "$output_dir" "$is_playlist"; then
        echo "EXISTS"
    else
        echo "NEW"
    fi
}

# 获取之前的链接状态
get_previous_link_status() {
    local url="$1"
    local file="$2"
    local file_name=$(basename "$file")
    local status_file="$DOWNLOAD_DIR/.${file_name}.status"
    
    if [ -f "$status_file" ]; then
        grep "^$url:" "$status_file" | cut -d: -f2 || echo "UNKNOWN"
    else
        echo "UNKNOWN"
    fi
}

# 保存链接状态
save_link_status() {
    local file="$1"
    local file_name=$(basename "$file")
    local status_file="$DOWNLOAD_DIR/.${file_name}.status"
    
    # 清空状态文件
    > "$status_file"
    
    # 保存每个链接的状态
    while IFS= read -r link; do
        if [ -n "$link" ]; then
            local status=$(get_link_status "$link" "$output_dir" "$is_playlist")
            echo "$link:$status" >> "$status_file"
        fi
    done < <(get_current_links "$file")
}

# 处理删除的链接
handle_removed_links() {
    local file="$1"
    local output_dir="$2"
    local is_playlist="$3"
    
    local current_links=$(get_current_links "$file")
    local previous_links=$(get_previous_links "$file")
    
    while IFS= read -r link; do
        if [ -n "$link" ] && ! echo "$current_links" | grep -q "$link"; then
            echo -e "${YELLOW}🗑️  链接已删除: $link${NC}"
            # 可以选择是否删除对应的文件
            # remove_old_files "$link" "$output_dir" "$is_playlist"
        fi
    done <<< "$previous_links"
}

# 删除旧文件
remove_old_files() {
    local url="$1"
    local output_dir="$2"
    local is_playlist="$3"
    
    # 从URL中提取视频ID或播放列表ID
    local video_id=""
    local playlist_id=""
    
    if [[ "$url" =~ watch\?v=([^&]+) ]]; then
        video_id="${BASH_REMATCH[1]}"
    elif [[ "$url" =~ playlist\?list=([^&]+) ]]; then
        playlist_id="${BASH_REMATCH[1]}"
    elif [[ "$url" =~ @([^/]+) ]]; then
        playlist_id="${BASH_REMATCH[1]}"
    fi
    
    if [ -n "$video_id" ]; then
        # 删除单个视频文件
        find "$output_dir" -name "*$video_id*" -delete 2>/dev/null
        echo -e "${YELLOW}已删除旧文件: $video_id${NC}"
    fi
    
    if [ -n "$playlist_id" ]; then
        # 删除播放列表目录
        local playlist_dir="$BATCH_VIDEO_DIR/$playlist_id"
        if [ -d "$playlist_dir" ]; then
            rm -rf "$playlist_dir"
            echo -e "${YELLOW}已删除播放列表目录: $playlist_dir${NC}"
        fi
    fi
}

# 显示帮助信息
show_help() {
    echo -e "${BLUE}YouTube高效下载脚本${NC}"
    echo "用法: $0 [选项] <YouTube链接>"
    echo ""
    echo "选项:"
    echo "  -h, --help              显示此帮助信息"
    echo "  -f, --format FORMAT     指定下载格式 (默认: $DEFAULT_FORMAT)"
    echo "  -d, --directory DIR     指定下载目录 (默认: $DOWNLOAD_DIR)"
    echo "                          单个视频: $SINGLE_VIDEO_DIR"
    echo "                          批量下载: $BATCH_VIDEO_DIR"
    echo "  -a, --audio-only        仅下载音频 (MP3格式)"
    echo "  -p, --playlist          下载整个播放列表"
    echo "  -q, --quality QUALITY   指定质量 (1080p, 720p, 480p, 360p)"
    echo "  -s, --subtitles         下载字幕"
    echo "  -b, --batch FILE        批量下载 (从文件读取链接)"
    echo "  -y, --sync              同步下载 (跳过已存在，只下载新增)"
    echo "  -v, --verbose           详细输出"
    echo ""
    echo "格式示例:"
    echo "  $0 https://www.youtube.com/watch?v=VIDEO_ID"
    echo "  $0 -a https://www.youtube.com/watch?v=VIDEO_ID"
    echo "  $0 -f 'best[height<=720]' https://www.youtube.com/watch?v=VIDEO_ID"
    echo "  $0 -p https://www.youtube.com/playlist?list=PLAYLIST_ID"
    echo "  $0 -y -b links.txt          # 同步下载，跳过已存在"
    echo ""
    echo "常用格式:"
    echo "  bestvideo+bestaudio/best    最佳质量 (默认)"
    echo "  worst                       最低质量 (最快下载)"
    echo "  best[height<=720]           720p或更低"
    echo "  best[ext=mp4]               MP4格式最佳质量"
}

# 下载单个视频
download_video() {
    local url="$1"
    local format="$2"
    local output_dir="$3"
    local audio_only="$4"
    local subtitles="$5"
    local verbose="$6"
    
    echo -e "${GREEN}开始下载:${NC} $url"
    
    # 构建yt-dlp命令
    local cmd="yt-dlp"
    
    # 添加格式参数
    if [ "$audio_only" = "true" ]; then
        cmd="$cmd -x --audio-format mp3 --audio-quality 0"
    else
        cmd="$cmd -f \"$format\""
    fi

    # 排序偏好：优先 m4a 音频、h264 视频、分辨率高、码率高
    cmd="$cmd -S \"acodec:m4a,vcodec:h264,res,br\""
    
    # 添加输出目录
    cmd="$cmd -o '$output_dir/%(title)s.%(ext)s'"
    
    # 添加字幕
    if [ "$subtitles" = "true" ]; then
        cmd="$cmd --write-subs --write-auto-subs --sub-lang zh-CN,en"
    fi
    
    # 添加详细输出
    if [ "$verbose" = "true" ]; then
        cmd="$cmd -v"
    fi
    
    # 添加其他优化参数
    cmd="$cmd --no-check-certificates --prefer-ffmpeg"
    
    # 添加重试和延迟参数
    cmd="$cmd --retries 3 --fragment-retries 3"
    cmd="$cmd --sleep-interval 2 --max-sleep-interval 5"
    
    # 强制使用MP4容器
    cmd="$cmd --merge-output-format mp4"

    # 下载完成后执行 iPhone 兼容性后处理（仅在最终文件移动后触发；检测非 H.264/AAC 则转码，并应用 faststart）
    if [ "$audio_only" != "true" ]; then
        cmd="$cmd --exec 'after_move:$SCRIPT_DIR/make_iphone_compatible.sh {}'"
    fi
    
    # 添加cookies支持（如果可用）
    if command -v yt-dlp &> /dev/null; then
        if yt-dlp --cookies-from-browser chrome --help &>/dev/null; then
            cmd="$cmd --cookies-from-browser chrome"
        fi
    fi
    
    # 添加YouTube认证跳过参数
    cmd="$cmd --extractor-args \"youtubetab:skip=authcheck\""
    
    # 添加URL
    cmd="$cmd '$url'"
    
    echo -e "${YELLOW}执行命令:${NC} $cmd"
    echo ""
    
    # 执行下载
    eval $cmd
    
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ 下载完成:${NC} $url"
    else
        echo -e "${RED}✗ 下载失败:${NC} $url"
    fi
    echo ""
}

# 批量下载
batch_download() {
    local file="$1"
    local format="$2"
    local output_dir="$3"
    local audio_only="$4"
    local subtitles="$5"
    local verbose="$6"
    local is_playlist="$7"
    
    if [ ! -f "$file" ]; then
        echo -e "${RED}错误: 文件不存在: $file${NC}"
        exit 1
    fi
    
    # 自动清洗去重一份链接文件，避免破损/无协议/非YouTube链接
    local sanitized_file="${file%.txt}_clean.txt"
    grep -Eo "https?://(www\\.)?(youtube\\.com/(shorts/[A-Za-z0-9_-]{11}|watch\\?v=[A-Za-z0-9_-]{11}|playlist\\?list=[A-Za-z0-9_-]+)|youtu\\.be/[A-Za-z0-9_-]{11})" "$file" | sort -u > "$sanitized_file" || true
    if [ -s "$sanitized_file" ]; then
        file="$sanitized_file"
    fi

    echo -e "${BLUE}开始批量下载，从文件: $file${NC}"
    echo ""
    
    local count=0
    local success=0
    
    while IFS= read -r line || [ -n "$line" ]; do
        # 跳过空行和注释行
        if [[ -z "$line" || "$line" =~ ^[[:space:]]*# ]]; then
            continue
        fi
        
        count=$((count + 1))
        echo -e "${BLUE}[$count]${NC} 处理链接: $line"
        
        # 如果是播放列表，为每个播放列表创建独立子文件夹
        local current_output_dir="$output_dir"
        if [ "$is_playlist" = "true" ]; then
            # 从URL中提取播放列表名称或ID
            local playlist_name=""
            if [[ "$line" =~ playlist\?list=([^&]+) ]]; then
                playlist_name="${BASH_REMATCH[1]}"
            elif [[ "$line" =~ @([^/]+) ]]; then
                playlist_name="${BASH_REMATCH[1]}"
            else
                playlist_name="playlist_$count"
            fi
            
            # 创建播放列表专用目录
            current_output_dir="$BATCH_VIDEO_DIR/$playlist_name"
            mkdir -p "$current_output_dir"
            echo -e "${YELLOW}创建播放列表目录:${NC} $current_output_dir"
        fi
        
        download_video "$line" "$format" "$current_output_dir" "$audio_only" "$subtitles" "$verbose"
        
        if [ $? -eq 0 ]; then
            success=$((success + 1))
        fi
        
        echo "----------------------------------------"
    done < "$file"
    
    echo -e "${GREEN}批量下载完成!${NC}"
    echo -e "总计: $count, 成功: $success, 失败: $((count - success))"
}

# 主函数
main() {
    local url=""
    local format="$DEFAULT_FORMAT"
    local output_dir="$DOWNLOAD_DIR"
    local audio_only="false"
    local playlist="false"
    local subtitles="false"
    local batch_file=""
    local verbose="false"
    local sync_mode="false"
    
    # 解析命令行参数
    while [[ $# -gt 0 ]]; do
        case $1 in
            -h|--help)
                show_help
                exit 0
                ;;
            -f|--format)
                format="$2"
                shift 2
                ;;
            -d|--directory)
                output_dir="$2"
                shift 2
                ;;
            -a|--audio-only)
                audio_only="true"
                shift
                ;;
            -p|--playlist)
                playlist="true"
                shift
                ;;
            -s|--subtitles)
                subtitles="true"
                shift
                ;;
            -b|--batch)
                batch_file="$2"
                shift 2
                ;;
            -y|--sync)
                sync_mode="true"
                shift
                ;;
            -v|--verbose)
                verbose="true"
                shift
                ;;
            -q|--quality)
                case "$2" in
                    1080p) format="bv*[height<=1080]+ba/b[height<=1080][acodec!=none][vcodec!=none][ext=mp4]/18";;
                    720p)  format="bv*[height<=720]+ba/b[height<=720][acodec!=none][vcodec!=none][ext=mp4]/18";;
                    480p)  format="bv*[height<=480]+ba/b[height<=480][acodec!=none][vcodec!=none][ext=mp4]/18";;
                    360p)  format="bv*[height<=360]+ba/b[height<=360][acodec!=none][vcodec!=none][ext=mp4]/18";;
                    *) echo -e "${RED}错误: 不支持的质量: $2${NC}"; exit 1;;
                esac
                shift 2
                ;;
            -*)
                echo -e "${RED}错误: 未知选项: $1${NC}"
                show_help
                exit 1
                ;;
            *)
                if [ -z "$url" ]; then
                    url="$1"
                else
                    echo -e "${RED}错误: 只能指定一个URL${NC}"
                    exit 1
                fi
                shift
                ;;
        esac
    done
    
    # 检查是否提供了URL或批量文件
    if [ -z "$url" ] && [ -z "$batch_file" ]; then
        echo -e "${RED}错误: 请提供YouTube链接或批量文件${NC}"
        show_help
        exit 1
    fi
    
    # 创建输出目录
    mkdir -p "$output_dir"
    
    # 如果是批量下载
    if [ -n "$batch_file" ]; then
        # 智能选择下载目录
        local final_output_dir="$output_dir"
        if [ "$output_dir" = "$DOWNLOAD_DIR" ]; then
            if [ "$playlist" = "true" ]; then
                final_output_dir="$BATCH_VIDEO_DIR"
            else
                final_output_dir="$SINGLE_VIDEO_DIR"
            fi
        fi
        
        # 根据模式选择下载方式
        if [ "$sync_mode" = "true" ]; then
            echo -e "${GREEN}启用同步下载模式${NC}"
            sync_download "$batch_file" "$format" "$final_output_dir" "$audio_only" "$subtitles" "$verbose" "$playlist"
        else
            batch_download "$batch_file" "$format" "$final_output_dir" "$audio_only" "$subtitles" "$verbose" "$playlist"
        fi
    else
        # 单个视频下载 - 使用单个视频目录
        local final_output_dir="$output_dir"
        if [ "$output_dir" = "$DOWNLOAD_DIR" ]; then
            final_output_dir="$SINGLE_VIDEO_DIR"
        fi
        
        download_video "$url" "$format" "$final_output_dir" "$audio_only" "$subtitles" "$verbose"
    fi
}

# 检查yt-dlp是否安装
if ! command -v yt-dlp &> /dev/null; then
    echo -e "${RED}错误: yt-dlp未安装${NC}"
    echo "请先安装yt-dlp: brew install yt-dlp"
    exit 1
fi

# 运行主函数
main "$@"
